package com.achievo.know.domain.infra.hibernate;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.achievo.know.domain.Category;
import com.achievo.know.domain.CategoryRepository;
import com.achievo.know.domain.User;
import com.dayatang.spring.repository.BaseEntityRepositoryHibernateSpring;

@Repository
public class CategoryRepositoryImpl extends BaseEntityRepositoryHibernateSpring<Category,Long> implements CategoryRepository {

	public CategoryRepositoryImpl() {
		super(Category.class);
	}

	@Override
	public List<Category> getRoots() {
		DetachedCriteria c=DetachedCriteria.forClass(Category.class);
		c.add(Restrictions.isNull("parent"));
		c.addOrder(Order.asc("position"));
		List<Category> list = getHibernateTemplate().findByCriteria(c);
		return list;
	}

	@Override
	public void removeCategory(Category c) {
		final String delRoleCateSql="delete from rams_role_r_category where CATEGORY_ID=?";
		final String delUserCateSql="delete from rams_user_r_category where CATEGORY_ID=? ";
		jdbcTemplate.update(delRoleCateSql,new Object[]{c.getId()});
		jdbcTemplate.update(delUserCateSql,new Object[]{c.getId()});
		remove(c);
	}

	
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	

	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	@Override
	public Set<Category> getUserCates(User loginUser) {
		Set<Category> cs=new HashSet<Category>();
		String sql="select CATEGORY_ID from rams_user_r_category where USER_ID=?";
		List<Map<String, Object>> list=jdbcTemplate.queryForList(sql, new Object[]{loginUser.getId()});
		for(Map<String, Object> m:list){
			Category c=get((Long) m.get("CATEGORY_ID"));
			if(c!=null){
				cs.add(c);
			}
		}
		return cs;
	}
}
